namespace CRM_Perf_BenchMark
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.WebTesting;
    using System.Net;
    using System.Text;
    using System.Xml;
    
    /// <summary>
    /// 1. Starts at Workplace homepage
    /// 2. Click on Activities
    /// 3. Click New button
    /// 4. Select Phone Call and click OK
    /// 5. Add random string to Subject and Description
    /// 6. Select Recipient (user) 
    /// 7. Select Regarding (account)
    /// 8. Click Save & Close
    /// </summary>

    public class CreatePhonecall : CrmWebTest
    {
        public void CreatePhonecall_PreWebTest(object sender, PreWebTestEventArgs e)
        {
            EntityRequest er = new EntityRequest();
            er.Type = EntityNames.Users;
            er.ReturnAs = EntityNames.Users;
            er.ParentID = EntityManager.Instance.OrgId;

            System.Collections.Hashtable Props = new System.Collections.Hashtable();

            if (e.WebTest.Context.ContainsKey("UserRole"))
            {
                Props.Add("role", e.WebTest.Context["UserRole"]);
            }
            
            EntityRequest AccountEr = new EntityRequest();
            AccountEr.Type = EntityNames.Accounts;
            AccountEr.ParentID = Guid.NewGuid();
            AccountEr.ReturnAs = EntityNames.Accounts;

            Props.Add(EntityNames.Accounts, new EntityRequest[] { AccountEr });

            er.Props = Props;

            System.Collections.Hashtable Entities = EntityManager.Instance.GetEntities(er);

            user = (CRMEntity)Entities[EntityNames.Users];
            account = (CRMEntity)Entities[EntityNames.Accounts];
            crmServer = user["CrmServer"];
            tokenKey = EntityManager.Instance.ReadTokenKey(user["organizationid"]);

            e.WebTest.UserName = user["domainName"];
            e.WebTest.Password = user["userpassword"];
            
            user2 = EntityManager.Instance.GetNextUser(new Guid(user["organizationid"]));

            orgId = new Guid(user["organizationid"]);
            ownerId = new Guid(user["systemuserid"]);
            fromId = new Guid(user["systemuserid"]);
            toId = new Guid(user2["systemuserid"]);
            regardingObjectId = new Guid(account["accountid"]);            
        }
      
        public void CreatePhonecall_PostWebTest(object sender, PostWebTestEventArgs e)
        {
            // Don't delete the entity till end of test run as it is deleted from crm.
            EntityManager.Instance.FreeEntity(user);
            EntityManager.Instance.FreeEntity(user2);
            EntityManager.Instance.FreeEntity(account);
        }

        public CreatePhonecall()
        {
            WebRequest.RegisterPrefix("crm", new crmRequestFactory());
            gridXml = GridXmlHelper.ActivitiesPageViewRefresh(-1, activitiesRefreshView, null);

            this.Proxy = null;            
            PreWebTest += new EventHandler<PreWebTestEventArgs>(CreatePhonecall_PreWebTest);
            PostWebTest += new EventHandler<PostWebTestEventArgs>(CreatePhonecall_PostWebTest);
        }

        public override IEnumerator<WebTestRequest> GetRequestEnumerator()
        {
            this.BeginTransaction("NavActivityHomepage");

            // Get the home page
            workplace_home_activities_aspx hp = new workplace_home_activities_aspx(user);
            yield return (hp);

            this.EndTransaction("NavActivityHomepage");

            this.BeginTransaction("CreatePhonecall");

            activities_dlg_create_aspx createPage = new activities_dlg_create_aspx(user);
            yield return (createPage);

            activities_phone_edit_aspx editPage = new activities_phone_edit_aspx(user);
            yield return (editPage);

            referer = editPage.lastResponse.ResponseUri.AbsoluteUri;

            _forms_FormScript_js_aspx f = new _forms_FormScript_js_aspx(user);
            f.etc = 4210;
            f.FormType = "main";
            f.FormName = "crmForm";
            headerItem = new WebTestRequestHeader("referer", referer);
            f.Headers.Add(headerItem);
            yield return (f);

            _controls_lookup_lookupmulti_aspx lookup = new _controls_lookup_lookupmulti_aspx(user);
            lookup.Class = "ActivityRecipient";
            lookup.objecttypes = "1,2,4,8";
            lookup.browse = 0;
            lookup.ShowNewButton = 1;
            lookup.ShowPropButton = 1;
            lookup.DefaultType = 0;
            yield return (lookup);

            _controls_lookup_lookupdata_aspx lookupdata = new _controls_lookup_lookupdata_aspx(user);
            lookupdata.Class = "ActivityRecipient";
            lookupdata.ObjectType = 1;
            lookupdata.objecttypes = "1,2,4,8";
            lookupdata.browse = 0;
            lookupdata.ShowNewButton = 1;
            lookupdata.ShowPropButton = 1;
            lookupdata.DefaultType = 0;
            lookupdata.Mode = 4;
            lookupdata.ColumnsOnly = 1;
            yield return (lookupdata);

            lookupdata = new _controls_lookup_lookupdata_aspx(user);
            lookupdata.Class = "ActivityRecipient";
            lookupdata.objecttypes = "1,2,4,8";
            lookupdata.browse = 0;
            lookupdata.ShowNewButton = 1;
            lookupdata.ShowPropButton = 1;
            lookupdata.DefaultType = 0;
            lookupdata.Mode = 4;
            lookupdata.ObjectType = 8;
            lookupdata.searchvalue = null;
            yield return (lookupdata);

            _controls_lookup_lookupsingle_aspx lookSingle = new _controls_lookup_lookupsingle_aspx(user);
            lookSingle.Class = "ActivityRegarding";
            lookSingle.objecttypes = "1,2,3,4,112,1010,1084,1088,1090,4402,4406,10000,10001";
            lookSingle.browse = 0;
            lookSingle.ShowNewButton = 1;
            lookSingle.ShowPropButton = 1;
            lookSingle.DefaultType = 0;
            yield return (lookSingle);

            editPage = new activities_phone_edit_aspx(user);
            editPage.crmFormSubmitXml = EntityXmlHelper.GetCreatePhonecallXml(ownerId, 8, toId, 8, regardingObjectId, 1); //e.Serialize();

            rpcInfo = Utils.GenerateWRPCToken(activities_phone_edit_aspx.url, user, tokenKey);
            editPage.CRMWRPCToken = rpcInfo.token;
            editPage.CRMWRPCTokenTimeStamp = rpcInfo.timeStamp;
            editPage.crmFormSubmitMode = 2;
            editPage.crmFormUserModified = true;
            editPage.crmFormSubmitObjectType = 4210;
            editPage.crmFormSubmitSecurity = 852023;
            editPage.crmFormSubmitOnline = 1;
            yield return (editPage);

            AppGridWebService.AppGridWebService ag = new AppGridWebService.AppGridWebService();
            CrmRequest wtr = null;

            try { ag.Refresh(gridXml); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
            }
            yield return (wtr);

            this.EndTransaction("CreatePhonecall");
        }

        private const string newIdMarker = @"SetQueryString(sLocation,""id"",""";
        private static string gridXml;
        private CRMEntity user;
        private CRMEntity user2;
        private CRMEntity account;
        private string crmServer;
        private string tokenKey;
        private string activitiesRefreshView = "00000000-0000-0000-00AA-000010001899";

        private Guid orgId;
        private Guid ownerId;
        private Guid toId;
        private Guid fromId;
        private Guid regardingObjectId;

        private string referer;
        private WRPCInfo rpcInfo;
        private WebTestRequestHeader headerItem;
    }
}